package com.diaohaiwen.framework.authority;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import com.diaohaiwen.common.obj.cache.RequestCache;
import com.diaohaiwen.common.config.AuthorityConfig;
import com.diaohaiwen.common.obj.login.LoginUser;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * @author 刁海文
 * @since 2023/6/11 17:44
 * @Remark
 */
@Order(1)
@Configuration
public class AuthorityWebConfig extends WebMvcConfigurationSupport {

    @Resource
    AuthorityConfig config;

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        // 自定义拦截器，logger MDC 请求信息初始化
        registry.addInterceptor(new SaInterceptor(handle -> {
                    // 校验登录
                    StpUtil.checkLogin();
                    // 设置用户名
                    LoginUser loginUser = AuthorityUtil.getLoginUser();
                    RequestCache.putAccountInfo(StpUtil.isLogin(), loginUser);
                }))
                .addPathPatterns(config.getPathPatterns())
                .excludePathPatterns(config.getExcludePathPatterns());
        super.addInterceptors(registry);
    }

    @Bean
    public StpLogic getStpLogicJwt() {
        return new StpLogicJwtForSimple();
    }

}
